package com.fingard.dsp.bank.directbank.bozz02;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.dbobj.receipt.ReceiptData;
import com.fingard.dsp.bank.dbobj.receipt.ReceiptDataHelper;
import com.fingard.dsp.bank.directConfig.ReceiptProConfig;
import com.fingard.dsp.bank.directbank.bankInterface.IReceiptPro;
import com.fingard.dsp.bank.reqrespobj.downloadreceipt.ReqQryReceipt;
import com.fingard.dsp.bank.reqrespobj.downloadreceipt.RetAtsReceipt;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7516HisTrans;
import com.fingard.io.FileHelper;
import com.fingard.text.StringHelper;
import com.fingard.util.SmbFileUtil;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

import java.io.File;
import java.util.Date;
import java.util.Map;

public class BOZZ02ReceiptPro extends BOZZ02Base implements IReceiptPro {

    @Override
    public RetAtsReceipt qryReceiptOneDay(ReceiptProConfig pConfig, ReqQryReceipt pReqReceipt, Date pOneDay) throws Exception {
        String queryDate=Format.Date8Format.format(pOneDay);//查询日期
        WriteBankLogLn("查询"+queryDate+"的回单开始");
        String receiptDownloadPath=bankFront.bankReceiptMainDir;//电子回单下载地址
        if(StringHelper.isNullOrEmpty(receiptDownloadPath)){
            throw new Exception("请配置银行前置机存回单文件的目录");
        }
        int count=0;//总查询回单数
        int receiptCountSuccess=0;//回单入库成功数
        int receiptCount=0;//重复入库条数
        //1、查询交易明细
        Req7516HisTrans tmpReq7516=new Req7516HisTrans(pReqReceipt.reqHeader);
        tmpReq7516.actNum = pReqReceipt.actNum;
        tmpReq7516.dateFrom = queryDate;
        tmpReq7516.dateTo = queryDate;
        Map<String,ReceiptData> queryJnlNoMap=getTransList(tmpReq7516);
        //2、获取交易流水号
        if(queryJnlNoMap!=null && queryJnlNoMap.size()>0){
            count=queryJnlNoMap.size();
            for(Map.Entry<String,ReceiptData> receiptMap:queryJnlNoMap.entrySet()){
                //3、获取回单文件名
                BOZZ02Header tmpBankHeader = new BOZZ02Header();
                tmpBankHeader.trsCode = "B2EDigitalReceiptInfoQuery";
                tmpBankHeader.erpTrsTimestamp = Format.DateTimeFormat.format(new Date());
                tmpBankHeader.erpJnlNo = getQryTransID();
                XmlTextWriter xmlWriter = new XmlTextWriter();
                writeCommonHead(xmlWriter, tmpBankHeader);
                xmlWriter.writeStartElement("Body");
                xmlWriter.writeStartElement("List");
                xmlWriter.writeStartElement("Map");
                xmlWriter.writeElementString("QueryJnlNo", receiptMap.getKey());//交易流水
                xmlWriter.writeElementString("AcNo", pReqReceipt.actNum);//账号
                xmlWriter.writeElementString("QueryDate", queryDate);//交易日期
                xmlWriter.writeEndElement();
                xmlWriter.writeEndDocument();
                String[] tmpStrRet = sendToBank(xmlWriter.toXmlString(), "B2EDigitalReceiptInfoQuery", true,"0");
                if (tmpStrRet[0].length() == 0) {
                    StringBuilder tmpSbMsg = new StringBuilder();
                    XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                    if (tmpBkReader != null) {
                        String tmpRespCode = tmpBkReader.getFirstText("/Message/Head/IBSReturnCode");
                        if ("000000".equals(tmpRespCode)) {
                            String fileName=tmpBkReader.getFirstTextNotNull("/Message/Body/FileName");//电子回单文件名
                            //4、下载电子回单文件
                            BOZZ02Header tmpBankHeader2 = new BOZZ02Header();
                            tmpBankHeader2.trsCode = "DigitalReceiptDownloadB2E|" + pReqReceipt.reqHeader.transSeqID;
                            tmpBankHeader2.erpJnlNo = getQryTransID();
                            tmpBankHeader2.erpTrsTimestamp = Format.DateTimeFormat.format(new Date());
                            XmlTextWriter xmlWriter2 = new XmlTextWriter();
                            writeCommonHead(xmlWriter2, tmpBankHeader2);
                            xmlWriter2.writeEndDocument();
                            String[] tmpStrRet2 = sendToBank(xmlWriter2.toXmlString(), "downloadFile", false, fileName
                                    , tmpBankHeader2.trsCode,"0");
                            if (tmpStrRet[0].length() == 0) {
                                StringBuilder tmpSbMsg2 = new StringBuilder();
                                XmlTextReader tmpBkReader2 = loadBankRespXmlReader(tmpStrRet2[1], tmpSbMsg2);
                                if (tmpBkReader2 != null) {
                                    String tmpRespCode2 = tmpBkReader2.getFirstText("/transaction/success");
                                    if (StringHelper.hasAnyChar(tmpRespCode2)) {
                                        WriteBankLogLn("文件"+fileName+"下载成功，开始移动");
                                        //5、移动电子回单文件到本地目录
                                        String receiptPath=receiptDownloadPath+File.separator+Format.Date10Format.format(new Date());
                                        if(receiptDownloadPath.contains("smb")){
                                            SmbFileUtil.smbDownloadInChar(pConfig.localSaveMainDir, receiptPath, fileName, new StringBuilder());
                                        }else {
                                            FileHelper.renameTo(receiptPath+File.separator+fileName,pConfig.localSaveMainDir+File.separator+fileName);
                                        }
                                        String pdfSavePath=pConfig.localSaveMainDir+File.separator+fileName;
                                        if(FileHelper.existFile(pdfSavePath)){
                                            WriteBankLogLn("文件"+fileName+"移动成功，开始数据入库");
                                            //6、填充电子回单信息
                                            ReceiptDataHelper receiptHelper = null;//回单数据保存类，分区分表
                                            try{
                                                ReceiptData eachData = receiptMap.getValue();
                                                /**回单唯一标识（在银行端的唯一标识（该账号的唯一），如招行的打印实例号）*/
                                                eachData.istNbr=receiptMap.getKey();
                                                /**回单关联号（回单编号）*/
                                                eachData.receiptNo=receiptMap.getKey();
                                                /**业务参考号*/
                                                eachData.busRef=receiptMap.getKey();
                                                /**银行流水号*/
                                                eachData.bnkSeqNo=receiptMap.getKey();
                                                /**银行代码，如工行102*/
                                                eachData.bank=banks;
                                                /**线路代码（来源渠道），如工行直联ICBC02*/
                                                eachData.srcSys=this.bankFront.bankCode;
                                                /**日期*/
                                                eachData.busDate=Integer.parseInt(queryDate);
                                                /**回单文件--本地文件相对路径*/
                                                eachData.localFile=StringHelper.getRelativePath(pdfSavePath, pConfig.localSaveMainDir);
                                                /**源文件路径*/
                                                eachData.srcFile=pdfSavePath;
                                                /**回单文件类型*/
                                                eachData.fileType="1";
                                                /**下载状态：指从银行下载该回单文件的状态，1未下载；2已下载；3下载失败；4下载中*/
                                                eachData.downState="2";
                                                /**下载时间*/
                                                eachData.downTime=new Date();
                                                /**下载信息，如果失败则为失败原因*/
                                                eachData.downInfo="下载成功";
                                                /**上传状态：指文件从银行端下载完成后，上传至ftp或ats或oss或客制化文件服务的状态，1未上传；2已上传；3上传失败；4上传中*/
                                                eachData.upState="1";
                                                /**推送状态：指文件上传完成后，回单数据推送至ats或客制化平台的状态，1未推送；2已推送；3推送失败；4推送中*/
                                                eachData.pushState="1";
                                                /**创建时间*/
                                                eachData.createdOn=new Date();
                                                /**最后修改时间*/
                                                eachData.lastModifiedOn=new Date();
                                                /**版本号*/
                                                eachData.rowVersion=1;
                                                receiptHelper = new ReceiptDataHelper(reqHeader.tenant, eachData.getBusDate());
                                                //回单数据记录入库
                                                int inRe = receiptHelper.insertIfNotExist(eachData,true);
                                                if(inRe>0){
                                                    receiptCountSuccess++;
                                                    WriteBankLogLn("文件"+fileName+"入库成功");
                                                }else if(inRe==0){
                                                    receiptCount++;
                                                    WriteBankLogLn("文件"+fileName+"重复入库");
                                                }else{
                                                    WriteBankLogLn("数据入库异常："+eachData.receiptNo+"\n");
                                                }
                                            }catch (Exception e){
                                                WriteBankLogLn("返回数据异常："+e.getMessage()+"\n");
                                            }finally {
                                                if(receiptHelper!=null){
                                                    receiptHelper.close();
                                                }
                                            }
                                        }else {
                                            WriteBankLogLn("移动电子回单异常，请重新查询"+"\n");
                                        }
                                    }else {
                                        WriteBankLogLn("返回数据异常："+tmpBkReader2.getFirstText("/transaction/error")+"\n");
                                    }
                                }else{
                                    WriteBankLogLn("返回数据异常："+tmpSbMsg2.toString()+"\n");
                                }
                            }else{
                                WriteBankLogLn("返回数据异常："+tmpStrRet[1]+"\n");
                            }
                        }else {
                            String respInfo = tmpBkReader.getFirstText("/Message/Head/IBSReturnMsg");
                            if (StringHelper.hasAnyChar(tmpBkReader.getFirstText("/transaction/error"))) {
                                respInfo = tmpBkReader.getFirstText("/transaction/error");
                            }
                            WriteBankLogLn("返回数据异常："+respInfo+"\n");
                        }
                    }else {
                        WriteBankLogLn("返回数据异常："+tmpSbMsg.toString()+"\n");
                    }
                }else {
                    WriteBankLogLn("返回数据异常："+tmpStrRet[1]+"\n");
                }
            }
        }else {
            WriteBankLogLn("未获取到"+queryDate+"的明细，请检查交易流水是否正常或重新查询");
        }
        WriteBankLogLn("查询总数："+count+"；已成功入库"+receiptCountSuccess+"条；重复数据"+receiptCount+"条");
        WriteBankLogLn("查询"+queryDate+"的回单结束");
        return null;
    }
}
